package gov.pbc.nn.kjgl.tech.view;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.service.IUserService;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;

import gov.pbc.nn.core.utils.SecurityUtils;
import gov.pbc.nn.kjgl.Constants;
import gov.pbc.nn.kjgl.entity.Technician;
import gov.pbc.nn.kjgl.entity.TechnicianHistory;
import gov.pbc.nn.kjgl.tech.dao.TechnicianDao;

@Component
public class TechnicianPR {

	@Autowired
	private TechnicianDao technicianDao;

	@Resource(name = IUserService.BEAN_ID)
	private IUserService us;

	@DataProvider
	public void getTechnician(Page<Technician> page, Criteria criteria) throws Exception {
		technicianDao.getAll(page, criteria);
	}

	@DataProvider
	public Technician getMyTechnician() throws Exception {
		return technicianDao.getMyTechnician();
	}

	@DataProvider
	public String getUserCname(String username) {
		if (StringUtils.isNotEmpty(username)) {
			IUser user = (IUser) this.us.loadUserByUsername(username);
			return user.getCname();
		}
		return null;
	}

	@DataProvider
	public List<Map<String, Object>> getUsers(String username) {
		return this.technicianDao.getUsers(username);
	}

	@DataProvider
	public void getTechnicianHistory(Page<TechnicianHistory> page, String originalId) throws Exception {
		this.technicianDao.getTechnicianHistory(page, originalId);
	}

	@Transactional
	@DataResolver
	public void saveAll(List<Technician> list) {
		technicianDao.save(list);
	}

	@Transactional
	@DataResolver
	public void save(Technician t) {
		List<Technician> list = new ArrayList<Technician>();
		list.add(t);
		technicianDao.save(list);
	}

	@Expose
	@Transactional
	public void delete(List<String> ids) {
		for (String id : ids) {
			technicianDao.delete(id);
		}
	}
	
	@Expose
	public boolean CheckRole() {
		  return SecurityUtils.containsRole(ContextHolder.getLoginUserName(), Constants.ROLE_KJRYGLY);
	}
}
